﻿namespace ap2.Phone.Core.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Data;
    using ap2.Phone.Core.Events;
    using Microsoft.Practices.Prism.Events;
    using Ninject;

    public class ViewModelLocator : IValueConverter
    {
        private readonly IKernel _Kernel;
        private KeyValuePair<string, object>[] parameters;
        private string _ViewModelsNamespace;

        public ViewModelLocator(string viewModelsNamespace, IKernel kernel, IEventAggregator eventAggregator)
        {
            this._ViewModelsNamespace = viewModelsNamespace;
            this._Kernel = kernel;
            eventAggregator.GetEvent<NavigatingEvent>().Subscribe(Navigating, true);
        }

        private void Navigating(NavigationArgs args)
        {
            this.parameters = args.Parameters;
        }

        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Type typeOfViewModel = Type.GetType(string.Format("{0}.{1}", this._ViewModelsNamespace, parameter));
            return this._Kernel.Get(typeOfViewModel
                ,new Ninject.Parameters.ConstructorArgument("parameters",this.parameters));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
